<template>
  <div class="common-page page-work-order" v-loading.fullscreen="loading">
    <div class="common-page__head">
      <comp-paths class="route" :paths="['/work', '/work/orders', $route.fullPath]"></comp-paths>
      <div class="title" v-if="order">
        <span class="text">{{ order.title }}</span>
        <span class="flag" v-for="tag in order.tags" :key="tag.id">{{ tag.name }}</span>
      </div>
      <div class="title" v-else></div>
    </div>
    <div class="common-page__body common-form" style="display: flex" v-if="order">
      <div class="rows" style="flex: 3 1 0; padding-right: 0">
        <div class="row row--head">
          <div class="name">基本信息</div>
          <div class="value">
            <span class="button button--edit" @click="setOrder()">编辑</span>
          </div>
        </div>
        <div class="row row--3x">
          <div class="name">
            <span v-if="order.company.type === 'company'">企业</span>
            <span v-else-if="order.company.type === 'project'">项目</span>
            <span v-else-if="order.company.type === 'area'">园区</span>
            <span>名称</span>
          </div>
          <div class="value">{{ order.company.name }}</div>
        </div>
        <div class="row row--3x">
          <div class="name">事项标题</div>
          <div class="value">{{ order.title }}</div>
        </div>
        <!-- <div class="row row--3x">
            <div class="name">调研服务小组：</div>
            <div class="value">{{ order.fwxz }}</div>
        </div> -->
        <div class="row row--3x">
          <div class="name">事项描述</div>
          <div class="value" style="white-space: pre-wrap">{{ order.content }}</div>
        </div>
        <div class="row row--3x">
          <div class="name">事项附件</div>
          <div class="value">
            <div style="padding: 1px 0">
              <comp-files-viewer :files="order.files" v-if="order.files.length > 0"></comp-files-viewer>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="name">事项对企业的影响程度</div>
          <div class="value">
            {{impactOptionsMap[order.impact] || ''}}
          </div>
        </div>
        <div class="row">
          <div class="name">事项分类</div>
          <div class="value">
            <span class="text" v-for="tag in order.tags" :key="tag.id">{{ tag.name }}</span>
          </div>
        </div>
        <div class="row" v-if="managerQuNums.includes(profile.number)">
          <div class="name">事项分类2</div>
          <div class="value">
            <span class="text">{{ order.tag2 }}</span>
          </div>
        </div>
        <div class="row">
          <div class="name">事项层面</div>

          <div class="value">
            <div v-if="order.level == 1 ">县级</div>
            <div v-else-if="order.level == 2 ">市级</div>
            <div v-else-if="order.level == 3 ">自治区级</div>
            <div v-else>
              <span v-if="order.dept.county.id">县级</span>
              <span v-else-if="order.dept.city.id">市级</span>
              <span v-else-if="order.dept.province.id">自治区级</span>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="name">事项状态</div>
          <div class="value">
            <span class="el-status--info" v-if="order.status === 'created'"></span>
            <span class="el-status--danger"
                  v-else-if="order.status === 'published' || order.status === 'return'"></span>
            <span class="el-status--warning" v-else-if="order.status === 'handling'"></span>
            <span class="el-status--success" v-else-if="order.status === 'finished'"></span>
            <span>{{ order.statusText }}</span>
          </div>
        </div>
        <div class="row row--2x">
          <div class="name">提交人</div>
          <div class="value">
            <span>{{ order.creator.name }}</span>
            <span style="margin-left: 0.5em; color: #aaa">{{ order.creator.number }}</span>
          </div>
        </div>
        <div class="row">
          <div class="name">提交时间</div>
          <div class="value">{{ order.createdAt }}</div>
        </div>
        <!--                <div class="row row&#45;&#45;2x">-->
        <!--                    <div class="name">负责工作队</div>-->
        <!--                    <div class="value">-->
        <!--                        <span>{{ order.hand.name }}</span>-->
        <!--                    </div>-->
        <!--                </div>-->
        <div class="row">
          <div class="name">服务专员</div>
          <div class="value">
            <span>{{ order.handler.name }}</span>
            <span style="margin-left: 0.5em; color: #aaa">{{ order.handler.number }}</span>
          </div>
        </div>
        <div class="row">
          <div class="name">办结时间</div>
          <div class="value">
            <span>{{ order.finishedAt }}</span>
          </div>
        </div>
        <div class="row">
          <div class="name">评价人</div>
          <div class="value">
            <span>{{ order.evaluatedCreator.name }}</span>
            <span style="margin-left: 0.5em; color: #aaa">{{ order.evaluatedCreator.number }}</span>
          </div>
        </div>
        <div class="row">
          <div class="name">评价打分</div>
          <div class="value">
            <span v-if="order.evaluated === 'yes'">{{ order.evaluatedStars }}星</span>
          </div>
        </div>
        <div class="row">
          <div class="name">办结类型：</div>
          <div class="value">
            <span v-if="order.bjlx=='0'">线上办结</span>
            <span v-if="order.bjlx=='1'">现场办结</span>

          </div>
        </div>
        <div class="row">
          <div class="name">办成情况：</div>
          <div class="value">
            <span v-if="order.bcqk=='0'">未办成</span>
            <span v-if="order.bcqk=='1'">已办成</span>

          </div>
        </div>
        <div class="row">
          <div class="name">服务小组：</div>
          <div class="value">
            <span>{{ order.fwxz }}</span>
          </div>
        </div>
        <div class="row">
          <div class="name">评价内容</div>
          <div class="value">
            <span v-if="order.evaluated === 'yes'">{{ order.evaluatedContent }}</span>
          </div>
        </div>
      </div>
      <div class="rows" style="flex: 2 1 0; flex-wrap: nowrap; flex-direction: column; padding-right: 0">
        <div class="row row--head">
          <div class="name">处理过程信息</div>
          <div class="value"></div>
        </div>
        <div class="row row--3x" style="flex: 1 1 0; overflow-x: hidden; overflow-y: auto">
          <div class="value">
            <comp-order-tracks :change-order="changeOrder" @deleteCountersign="handleDeleteCountersign" :order="order" @change="change"></comp-order-tracks>
          </div>
        </div>
      </div>
    </div>
    <comp-dialog title="编辑基本信息" width="748px" ref="orderSetForm">
      <el-form size="small" label-width="98px" @submit.native.prevent v-if="orderSetForm">
        <el-form-item label="企业/项目：" required>
          <el-tag
            style="margin-right: 10px; max-width: 450px"
            disable-transitions
            v-if="orderSetForm.company.id"
          >{{ orderSetForm.company.name }}</el-tag
          >
          <el-button
            type="plain"
            icon="el-icon-refresh"
            @click="setOrder('order-company')"
            v-if="order.company.id"
          >更换企业/项目</el-button
          >
          <el-button
            type="plain"
            icon="el-icon-plus"
            @click="setOrder('order-company')"
            v-else
          >选择企业/项目</el-button
          >
        </el-form-item>
        <el-form-item label="问题来源：" required>
          <el-select
            v-model="orderSetForm.wtly"
            style="width: 600px"
            placeholder="请选择"
            @change="setOrder('validate')"
          >
            <el-option key="0" label="自治区调研" value="0"></el-option>
            <el-option key="1" label="市县调研" value="1"></el-option>
            <el-option key="2" label="企业提交" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调研服务组：" >
          <el-select v-model="orderSetForm.fwxz"
                     clearable
                     style="width: 600px" placeholder="请选择"
                     @change="setOrder('validate')">
            <!--                        <el-option key="18" label="市县自主调研" value="市县自主调研"></el-option>-->

            <el-option key="0" label="第一组" value="第一组"></el-option>
            <el-option key="1" label="第二组" value="第二组"></el-option>
            <el-option key="2" label="第三组" value="第三组"></el-option>
            <el-option key="3" label="第四组" value="第四组"></el-option>
            <el-option key="4" label="第五组" value="第五组"></el-option>
            <el-option key="5" label="第六组" value="第六组"></el-option>
            <el-option key="6" label="第七组" value="第七组"></el-option>
            <el-option key="7" label="第八组" value="第八组"></el-option>
            <el-option key="8" label="第九组" value="第九组"></el-option>
            <el-option key="9" label="第十组" value="第十组"></el-option>
            <el-option key="10" label="第十一组" value="第十一组"></el-option>
            <el-option key="11" label="第十二组" value="第十二组"></el-option>
            <el-option key="12" label="第十三组" value="第十三组"></el-option>
            <el-option key="13" label="第十四组" value="第十四组"></el-option>
            <el-option key="14" label="第十五组" value="第十五组"></el-option>
            <el-option key="15" label="第十六组" value="第十六组"></el-option>
            <el-option key="16" label="第十七组" value="第十七组"></el-option>
            <el-option key="17" label="厅局调研" value="厅局调研"></el-option>
            <el-option key="18" label="专项行动" value="专项行动"></el-option>
            <el-option key="19" label="领导交办事项" value="领导交办事项"></el-option>
            <el-option key="20" label="投资工作专班" value="投资工作专班"></el-option>
            <el-option key="21" label="市县自主调研" value="市县自主调研"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题层级：" required>
          <el-select
            v-model="orderSetForm.level"
            style="width: 600px"
            placeholder="请选择"
            @change="setOrder('validate')"
          >
            <el-option key="1" label="区县级" value="1"></el-option>
            <el-option key="2" label="市级" value="2"></el-option>
            <el-option key="3" label="自治区级" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事项标题：" required>
          <el-input ref="orderSetFormTitle" type="textarea" v-model="orderSetForm.title" style="width: 600px"
                    placeholder="请输入" :maxlength="100" :rows="2" resize="none" :readonly="loading"
                    @change="setOrder('validate')"></el-input>
        </el-form-item>

        <el-form-item label="事项描述：">
          <el-input type="textarea" v-model="orderSetForm.content" style="width: 600px" placeholder="请输入"
                    :maxlength="1000" :rows="10" resize="none" :readonly="loading"
                    @change="setOrder('validate')"></el-input>
        </el-form-item>
        <el-form-item label="事项对企业的影响程度：">
          <el-select v-model="orderSetForm.impact">
            <el-option v-for="item in impactOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事项分类：">
          <el-cascader
            style="width:600px"
            v-model="tagsSelect"
            :options="tagsTree"
            :props="{
                label:'name',
                value:'id'
              }"
            @change="setOrder('validate')"></el-cascader>
        </el-form-item>
        <el-form-item label="事项分类2：" v-if="managerQuNums.includes(profile.number)">
          <div style="width: 600px">
            <el-input
              type="text"
              v-model="orderSetForm.tag2"
              style="width: 600px"
              placeholder="请输入"
              :readonly="loading"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="涉及金额：" v-if="tagsSelect.includes('202216522600950317')" required>
          <div style="width: 600px">
            <el-input
              type="text"
              v-model="orderSetForm.money"
              style="width: 600px"
              placeholder="请输入"
              :readonly="loading"
            >
              <span slot="append">万元</span>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="需求金额：" v-if="tagsSelect.includes('202216522600880316')" required>
          <div style="width: 600px">
            <el-input
              type="text"
              v-model="orderSetForm.money"
              style="width: 600px"
              placeholder="请输入"
              :readonly="loading"
            >
              <span slot="append">万元</span>
            </el-input>
          </div>
        </el-form-item>

        <el-form-item label="事项联系人：" required>
          <div style="width: 600px">
            <el-input
              type="text"
              v-model="orderSetForm.orderContract"
              style="width: 600px"
              placeholder="请输入"
              :readonly="loading"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="联系人电话：" required>
          <div style="width: 600px">
            <el-input
              type="text"
              v-model="orderSetForm.contractPhone"
              style="width: 600px"
              placeholder="请输入"
              :readonly="loading"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="收集事项时间：" required>
          <div style="width: 600px">
            <el-date-picker
              v-model="orderSetForm.getOrderTime"
              type="datetime"
              style="width: 600px"
              placeholder="请选择"
              :readonly="loading"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-check" @click="setOrder('submit')">保存</el-button>
          <el-button type="plain" icon="el-icon-close" @click="setOrder('end')">放弃</el-button>
        </el-form-item>
      </el-form>
    </comp-dialog>
    <comp-dialog title="选择分类" width="60vw" height="80vh" ref="tagPicker">
      <comp-order-of-tags style="height: 100%" ref="tagPickerList" select>
        <template #foot="scope">
          <el-button type="primary" size="small" icon="el-icon-check"
                     @click="setOrder('pick-tag-submit', scope.selects)">选择完成（已选{{ scope.selects.length }}个）
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-close" @click="setOrder('pick-tag-end')">放弃</el-button>
        </template>
      </comp-order-of-tags>
    </comp-dialog>

<!--    选择企业-->
    <comp-dialog
      title="选择企业/项目"
      width="80vw"
      height="80vh"
      ref="companyPicker"
    >
      <comp-companys
        style="height: 100%"
        ref="companyPickerList"
        limit="dept"
        v-if="orderSetForm"
      >
        <template #body="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-check"
            @click.stop="setOrder('order-company', scope.data.id)"
          >选择</el-button
          >
        </template>
        <template #foot="scope">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-close"
            @click="setOrder('order-company-end')"
          >放弃</el-button
          >
        </template>
      </comp-companys>
    </comp-dialog>
  </div>
</template>

<script>
import mixin from "../mixin";
import {string, int, deepCopy, cache} from "../util";

import treeData from '../plugins/treeData'

export default {
  name: "page-work-order",
  title: "事项详情",
  nodes: ["/menu/work"],
  childs: [],
  mixins: [mixin],
  data: () => ({
    loading: false,
    orderId: "",
    order: null,
    orderSetForm: null,
    fwxz: null,
    managerQuNums: managerQuNums,
    changeOrder:false,
    impactOptions:[
      {label:'轻微影响',value:'1'},
      {label:'一般影响',value:'2'},
      {label:'重大影响',value:'3'},
    ],
    impactOptionsMap:{
      '1':'轻微影响',
      '2':'一般影响',
      '3':'重大影响',
    },
    tags:[],
    tagsTree: [],
    tagsSelect:[],
  }),
  methods: {
    change(value) {
      this.order = value
    },
    async setOrder(action, data) {
      if (this.loading) return;
      let form = this.orderSetForm;
      if (!action || action === "start") {
        this.orderSetForm = deepCopy(this.order);
        this.orderSetForm.getOrderTime = this.order.getOrderTime
        console.log('this.order',this.order)
        console.log('this.orderSetForm',this.orderSetForm)
        this.tagsSelect = this.order.tags.map(x=>x.id)
        // 加载分类
        let tags = await this.plugins.user
          .getOrderOfTags({
            linage:1000
          })
          .then((res) => (res.code === 0 ? res.data : []));
        this.tags = tags.list
        this.tagsTree = treeData.arrayToTree(tags.list, "id", "parentId", "");

        this.$nextTick(() => {
          this.$refs.orderSetForm.init();
          // this.$refs.orderSetFormTitle.focus()
        });
      } else if (action === "validate") {
        let error = "";

        form.fwxz = string(form.fwxz).trim();
        form.title = string(form.title).trim();
        form.level = string(form.level)
        error = error || (form.company.id ? "" : "请先选择企业/项目！");
        // error = error || (form.fwxz ? "" : "请先选择调研服务组！");
        error = error || (form.title ? "" : "请输入事项标题！");
        form.tags = this.tags.filter(x=>this.tagsSelect.includes(x.id))
        error = error || (form.tags.length >= 1 ? "" : "事项分类必填！");
        error = error || (form.content ? "" : "请先输入事项描述！");
        error = error || (form.orderContract ? "" : "请先输入事项联系人！");
        error = error || (form.contractPhone ? "" : "请先输入联系人电话！");
        error = error || (form.getOrderTime ? "" : "请选择事项收集时间！");
        error = error || (form.impact ? "" : "请选择事项对企业的影响程度！");


        // 判断金额
        if(
          (
            this.tagsSelect.includes('202216522600950317')
            || this.tagsSelect.includes('202216522600880316')
          )
        ){
          error = error || (form.money ? "" : "请输入金额！");
        }else{
          form.money = null
        }

        if (error) this.plugins.modal.toast(error, "error");
        return !error;
      } else if(action == 'order-company'){
        let companyId = data;
        if (companyId) {
          this.loading = true;
          let order = this.orderSetForm
          let profile = this.profile
          this.plugins.user.getCompany(companyId).then((res) => {
            this.loading = false;
            if (res.code === 0) {
              let company = (order.company = res.data);
              let depts = (company.depts = company.depts.filter((dept) =>
                profile.depments.some((depment) => depment.dept.id === dept.id)
              ));
              if (depts.length === 1) {
                order.dept.id = depts[0].id;
                order.dept.name = depts[0].name;
              } else {
                order.dept.id = "";
                order.dept.name = "";
              }
              this.setOrder("validate");
              this.setOrder("order-company-end");
            } else {
              order.company = this.plugins.user.formatCompany();
              order.dept.id = "";
              order.dept.name = "";
              this.setOrder("validate");
              this.setOrder("order-company-end");
              this.plugins.modal.toast(
                "加载失败<br>" + res.code + "：" + res.msg,
                "error"
              );
            }
          });
        } else {
          this.$refs.companyPicker.init();
          this.$nextTick(() => this.$refs.companyPickerList.init());
        }
      } else if(action == 'order-company-end'){
        this.$refs.companyPicker.close();
      } else if (action === "pick-tag-start") {
        this.$refs.tagPicker.init();
        this.$nextTick(() => this.$refs.tagPickerList.init());
      } else if (action === "pick-tag-submit") {
        let tags = data;
        if (tags) form.tags = tags.splice(0, 3);
        this.setOrder("validate");
        this.setOrder("pick-tag-end");
      } else if (action === "pick-tag-end") {
        this.$refs.tagPicker.close();
      } else if (action === "clear-tags") {
        form.tags.splice(0);
        this.setOrder("validate");
      } else if (action === "submit") {
        if (!this.setOrder("validate", true)) return;
        this.loading = true;
        this.plugins.user.setOrderManager(form).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.plugins.modal.toast("保存成功！", "success");
            this.setOrder("end");
            this.init();
          } else {
            this.plugins.modal.alert("保存失败", res.code + "：" + res.msg, "error");
          }
        });
      } else if (action === "end") {
        this.$refs.orderSetForm.close();
      }
    },
    destroy() {
      if (this.loading) return;
      return true;
    },
    init() {
      if (this.loading) return;
      let query = this.$route.query;
      let order = null;
      this.loading = true;
      this.orderId = query.orderId;
      this.order = cache(query.orderId);
      this.$root.$refs.navbar.init();
      this.plugins.user.call(async () => {
        let res = await this.plugins.user.init();
        if (res.code === 0) {
        }
        return res;
      }, async () => {
        if (this.access(this.$route.name)) return {code: 0};
        return this.env.xhrErrors.find((error) => error.code === 4);
      }, async () => {
        let res = await this.plugins.user.getOrder(query.orderId);
        if (res.code === 0) order = res.data;
        if (res.code === 0) {
          if (order.tracks) {
            for (let track of order.tracks) {
              let handler = track.handler;
              let depments = handler.depments.splice(0);
              for (let depment of depments) depment.dept.id === track.dept.id && handler.depments.push(depment);
              let creator = order.creator;
              let matched = track.type === "start" && track.handler.id === creator.id && creator.role === "holder";
              if (matched) order.creator = track.handler;
            }
          }

          for (let creator of [order.creator, order.evaluatedCreator]) {
            let employees = creator.employees.splice(0);
            for (let employee of employees) employee.company.id === order.company.id && creator.employees.push(employee);
          }
        }
        return res;
      }).then((res) => {
        this.loading = false;
        this.$root.$refs.navbar.init();
        if (res.code === 0) {
          console.log('res.data',res.data)
          this.order = cache(query.orderId, order);
          this.changeOrder = !this.changeOrder
        } else if (res.code === 2) {
          this.$root.$refs.navbar.login();
        } else {
          this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/work/orders"));
        }
      });
    },
    handleDeleteCountersign(e) {
      if(!e?.id){
        this.plugins.modal.toast('该转派有异常不支持删除',"error")
        return
      }

      this.plugins.modal.alert("", "确定删除该转派", "warning", ["确定", "再想想"]).then((ok) => {
        if (!ok){
          return;
        }
        this.loading = true
        this.plugins.user.deleteCounterSignByAdmin(e.id).then((res) => {
          console.log(res)
          if(res.code == 0){
            // 删除成功
            this.plugins.modal.toast('删除成功',"success")
            this.loading = false
            // 清除缓存
            cache(this.order.orderId, null)
            this.init()
          }
        }).finally(e=>{
          this.loading = false
        })
      });
    }
  },
};
</script>

<style lang="scss">
.page-work-order {
  overflow: hidden;
}
</style>
